package router

import (
	"fmt"
	"i18n-template/components"
	"i18n-template/table"
	"i18n-template/utils"

	"github.com/gin-gonic/gin"
)

func UsePageIndexRouter(router *gin.RouterGroup) {
	router.POST("", func(context *gin.Context) {
		index := table.Index{}
		err := context.ShouldBind(&index)
		if err != nil {
			utils.FailResponse(context, "绑定数据失败！", err.Error())
			return
		}
		// 1.1 查找轮播图图片
		_, err = index.FindIndexByLang(index)
		if err != nil {
			//	生成第一个轮播图数据
			err = index.GenerateIndex(index)
			if err != nil {
				utils.FailResponse(context, "生成轮播图失败", err.Error())
				return
			}
		}
		// 1.2 更新轮播图数据
		index.UpdateIndexByLang(index)
		utils.SuccessResponse(context, "请求成功", "")
	})
	router.GET("", func(context *gin.Context) {
		lang := context.Query("lang")
		index := table.Index{Language: lang}
		byLang, err := index.FindIndexByLang(index)
		if err != nil {
			utils.FailResponse(context, "查询失败", err.Error())
			return
		}
		fmt.Println("=> GET")
		// 获取4个类型的前3个
		var i []table.Inductance
		var p []table.Photoelectric
		var m []table.Measurement
		var c []table.Capacitance
		components.DB.Model(&table.Inductance{}).
			Where("language = ?", lang).
			Limit(4).
			Find(&i)
		components.DB.Model(&table.Photoelectric{}).
			Where("language = ?", lang).
			Limit(4).
			Find(&p)
		components.DB.Model(&table.Measurement{}).
			Where("language = ?", lang).
			Limit(4).
			Find(&m)
		components.DB.Model(&table.Capacitance{}).
			Where("language = ?", lang).
			Limit(4).
			Find(&c)
		data := struct {
			Swiper        table.Index           `json:"swiper"`
			Inductance    []table.Inductance    `json:"inductance"`
			Photoelectric []table.Photoelectric `json:"photoelectric"`
			Measurement   []table.Measurement   `json:"measurement"`
			Capacitance   []table.Capacitance   `json:"capacitance"`
		}{
			Swiper:        byLang,
			Inductance:    i,
			Photoelectric: p,
			Measurement:   m,
			Capacitance:   c,
		}
		utils.SuccessResponse(context, "查询成功", data)
	})
}
